package com.atguigu.yygh.hosp.testmongodb;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.hosp.mapper.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/mongo2")
public class TestMongo2 {

    @Autowired
    private UserRepository userRepository;

    //添加
    @GetMapping("create")
    public R createUser() {
        User user = new User();
        user.setAge(20);
        user.setName("张三");
        user.setEmail("3332200@qq.com");

        //可以判断，如果有id就是修改，没有id就是查询
        User save = userRepository.save(user);
        System.out.println("save = " + save);
        return R.ok().data("user",user);
    }

    //查询所有
    @GetMapping("findAll")
    public R findUser() {
        List<User> users = userRepository.findAll();

        return R.ok().data("users",users);
    }

    //id查询
    @GetMapping("findId")
    public R getById() {
        User user = userRepository.findById("60b8d57ed539ed5b124942de").get();

        return R.ok().data("user",user);
    }

    //条件查询
    @GetMapping("findQuery")
    public R findUserList() {
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);

        Example<User> example = Example.of(user);

        List<User> users = userRepository.findAll(example);

        return R.ok().data("users",users);
    }

    //模糊查询
    @GetMapping("findLike")
    public R findUsersLikeName() {
        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        User user = new User();
        user.setName("san");

        Example<User> example = Example.of(user,matcher);

        List<User> users = userRepository.findAll(example);

        return R.ok().data("users",users);
    }

    //分页查询
    @GetMapping("findPage")
    public R findUsersPage() {
        //根据字段age进行降序排列
        Sort sort = Sort.by(Sort.Direction.DESC,"age");

        //设置分页查询
        Pageable pageable = PageRequest.of(0,10,sort);

        //使用模糊查询
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        User user = new User();
        user.setName("san");
        Example<User> userExample = Example.of(user, matcher);

        Page<User> page = userRepository.findAll(userExample, pageable);

        List<User> users = page.getContent();

        return R.ok().data("users",users);

    }

}
